const Koa = require("koa");
const Router = require("koa-router");
const logger = require("koa-logger");
const bodyParser = require("koa-bodyparser");
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const router = new Router();

const homePage = fs.readFileSync(path.join(__dirname, "index.html"), "utf-8");

// 首页
router.get("/", async (ctx) => {
  ctx.body = homePage;
});


// 获取计数
router.get("/api/count", async (ctx) => {
  ctx.body = {
    code: 0,
    data: 2025,
  };
  console.log(result);
});
const host = 'https://api.weixin.qq.com'
// 小程序调用，获取微信 Open ID
router.get("/api/wx_openid", async (ctx) => {
  if (ctx.request.headers["x-wx-source"]) {
    ctx.body = ctx.request.headers["x-wx-openid"];
  }
});
router.get('/match_rules', async (ctx) => {

  const res = await axios.post(host + '/wxa/business/gamematch/getallmatchrule')
  ctx.body = res.data
})
router.put('/match_rules/state', async (ctx) => {
  const { match_id, open_state } = ctx.request.body
  const res = await axios.post(host + '/wxa/business/gamematch/setmatchopenstate', { match_id, open_state })
  ctx.body = res.data
})
router.put('/match_rules', async (ctx) => {
  const { team_count, need_user_info, match_id, team_member_count } = ctx.request.body
  const form = {
    team_count,
    match_id,

    team_member_count,
    need_room_service_info: 1,
    game_room_info: {
      need_user_info,
      game_tick: 33,
      start_percent: 0,
      udp_reliability_strategy: 3
    }
  }
  console.log(form)
  const res = await axios.post(host + '/wxa/business/gamematch/updatematchrule', form)
  ctx.body = res.data
})
router.post('/match_rules', async (ctx) => {
  const { team_count, need_user_info, team_member_count } = ctx.request.body
  const form = {
    team_count,
    team_member_count,
    need_room_service_info: 1,
    game_room_info: {
      need_user_info,
      game_tick: 33,
      start_percent: 0,
      udp_reliability_strategy: 3
    }
  }
  const res = await axios.post(host + '/wxa/business/gamematch/creatematchrule', form)
  ctx.body = res.data
})
router.delete('/match_rules', async (ctx) => {
  const { match_id } = ctx.request.body
  const res = await axios.post(host + '/wxa/business/gamematch/deletematchrule', { match_id })
  ctx.body = res.data
})
const app = new Koa();
app
  .use(logger())
  .use(bodyParser())
  .use(router.routes())
  .use(router.allowedMethods());

const port = process.env.PORT || 80;
async function bootstrap() {
  app.listen(port, () => {
    console.log("启动成功", port);
  });
}
bootstrap();
